package com.dtb.vote_rank.controller;

import com.alibaba.fastjson.JSONObject;
import com.dtb.vote_rank.cache.CacheSingleService;
import com.dtb.vote_rank.common.Constant;
import com.dtb.vote_rank.entity.ProducerEntity;
import com.dtb.vote_rank.servcie.VoteService;
import com.dtb.vote_rank.util.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author:ChengJian
 * @Description:
 * @Date: Created in 下午3:36 2018/11/15
 */
@Controller
@RequestMapping(value = "/vote")
public class VoteRankController {

    @Autowired
    VoteService voteService;

    @Autowired
    CacheSingleService cacheService;

    @PostMapping(value = "/create")
    @ResponseBody
    public String create(@RequestBody ProducerEntity producerEntity){
        ProducerEntity result = voteService.addProducer(producerEntity);
        voteService.addRank(result,1);
        return "SUCCESS";
    }

    @GetMapping(value = "/delete")
    @ResponseBody
    public String delete(int id){
        voteService.deleteProducer(id);
        voteService.removeRank(1,id);
        return "success";
    }

    @PostMapping(value = "/update")
    @ResponseBody
    public String update(@RequestBody ProducerEntity producerEntity){
        ProducerEntity result = voteService.updateMysql(producerEntity);
        voteService.addRank(result,1);
        return "success";
    }

    //获取所有的参加排行的列表
    @GetMapping(value = "/list")
    @ResponseBody
    public String getList(HttpServletRequest request){

        Map<String,Object> map = new HashMap<>();
        int page     = ServletRequestUtils.getIntParameter(request,"page",0);
        int pageSize = ServletRequestUtils.getIntParameter(request,"pageSize",10);
        int sortType = ServletRequestUtils.getIntParameter(request,"sortType",1);

        //1 按照rank排名 0 按照时间排序 2 按照权重排序
        //1 升序  -1 降序
        switch (sortType){
            case 1:
                map.put("rank",1);
                break;
            case 2:
                map.put("weight",-1);
                break;
            case 0:
                map.put("time",1);
                break;
            default:
                map.put("rank",1);
                break;
        }
        List<ProducerEntity> list = voteService.getList(map);
        return JSONObject.toJSONString(list);
    }

    //点赞，投票
    @PostMapping(value = "/vote")
    @ResponseBody
    public String vote(int id,int type){

        JSONObject result = new JSONObject();
        //查询投票活动是否开启
        String isVote = cacheService.get(Constant.ACTIVITY_IS_VOTE_KEY);

        if (StringUtils.isEmpty(isVote) && isVote.equals("2")){
            result.put("code",1001);
            result.put("message","投票活动已关闭～");
            return result.toJSONString();
        }

        String today = DateUtils.getDateToyyyyMMdd(new Date());

        ProducerEntity producer  = voteService.getProduce(id);

        if (producer.getStatus() != 1){
            result.put("code",1002);
            result.put("message","投票失败，未通过审核");
            return result.toJSONString();
        }

        String key = Constant.VOTE_FLAG+type+"_"+id+"_"+today;
        String str = cacheService.get(key);
        int vote   = 0;
        boolean i  = false;

        if (StringUtils.isEmpty(str)){
            vote = 1;
            i    = true;
            voteService.vote(id,vote,i,type);
            //保留一天一次投票缓存信息
            cacheService.setex(key,24*60*60,id+"");
            //接下来可以保留用户投票信息记录，略....
            result.put("code",200);
            result.put("message","投票成功!");
        }else {
            result.put("code",210);
            result.put("message","您今天已经投过票!");
        }
        return "SUCCESS";
    }

    /**
     *
     * @Description：随机获取排行榜，不按名次，随机 count: 要随机展示的个数
     * @Date：2018/11/21 下午3:16
     * @Author：ChengJian
     * @UpdateRemark:
     * @Version:1.0
     *
     */
    @GetMapping(value = "/getIndexInfo")
    @ResponseBody
    public String getIndexInfo(int type,int id,int count){

        JSONObject result = new JSONObject();

        String today = DateUtils.getDateToyyyyMMdd(new Date());
        String key   = Constant.VOTE_FLAG+type+"_"+id+today;
        String str   = cacheService.get(key);
        Set<String> voteIdSet = new HashSet<>();
        if (!StringUtils.isEmpty(str)){
            voteIdSet.add(str);
        }

        List<ProducerEntity> list = voteService.getRandom(type,count,voteIdSet);

        result.put("data",list);
        result.put("code",200);
        result.put("message","随机获取排行成功");
        result.put("success",true);
        return result.toJSONString();
    }


    //获取前几名
    @GetMapping(value = "/getTop")
    @ResponseBody
    public String getTop(HttpServletRequest request){

        int page     = ServletRequestUtils.getIntParameter(request,"page",0);
        int pageSize = ServletRequestUtils.getIntParameter(request,"pageSize",10);
        int id       = ServletRequestUtils.getIntParameter(request,"id",0);
        int type     = ServletRequestUtils.getIntParameter(request,"type",1);

        JSONObject result = new JSONObject();
        if (id == 0){
            result.put("code",210);
            result.put("message","id错误");
            result.put("success",false);
            return result.toJSONString();
        }

        String today = DateUtils.getDateToyyyyMMdd(new Date());
        String key   = Constant.VOTE_FLAG+type+"_"+id+"_"+today;
        //获取今日投票的id
        String voteUserId = cacheService.get(key);

        JSONObject data = voteService.getTop(type,page,pageSize,voteUserId);

        result.put("data",data);
        result.put("code",200);
        result.put("message","成功获取排行榜前几名");
        return result.toJSONString();
    }

   @PostMapping(value = "/test")
   @ResponseBody
   public String test(int id,int type){
       ProducerEntity producer = voteService.getProduce(id);
       voteService.addRank(producer,type);
       return "success";
   }



   //将缓存中的数据同步更新到数据库中
   @GetMapping(value = "/flushCacheToMysql")
   @ResponseBody
   public String flushCacheToMysql(HttpServletRequest request){

        int id = ServletRequestUtils.getIntParameter(request,"id",0);

        if (id != 0){
            //更新该id对应的producer
        }else {
          //更新所有
            Map<String,Object> map = new HashMap<>();
            List<ProducerEntity> list = voteService.getList(map);
            for (ProducerEntity producer :list){
                ProducerEntity info = voteService.getVoteInfo(producer.getId(),1);
                producer.setVoteNum(info.getVoteNum());
                producer.setRank(info.getRank());
                voteService.updateMysql(producer);
            }
        }
        return "success";
   }

   /**
    *
    * @Description：将数据库的数据更新到缓存中
    * @Date：2018/11/21 下午3:28
    * @Author：ChengJian
    * @UpdateRemark:
    * @Version:1.0
    *
    */
   @GetMapping(value = "/flushToCache")
   @ResponseBody
   public String flushToCache(){
       //查询所有
       Map<String,Object> map = new HashMap<>();
       List<ProducerEntity> list = voteService.getList(map);
       for (ProducerEntity producerEntity :list){
           if (producerEntity.getStatus() == 1){
               voteService.addRank(producerEntity,producerEntity.getType());
           }else {
               voteService.removeRank(producerEntity.getType(),producerEntity.getId());
           }
       }
       return "success";
   }

}
